package com.dt.common.validation.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.dt.common.validation.ValidatorIdentity;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.itf.AbandonedDefinition;
import com.dt.common.validation.itf.ValidationDefinition;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ObjectValidationDefinition {

	private ValidatorIdentity identity;
	private Set<ValidationDefinition> definitions = new HashSet<>();

	public ObjectValidationDefinition(ValidatorIdentity identity) {
		this.identity = identity;
	}

	public Collection<ValidationDefinition> getDefinitions() {
		return definitions;
	}

	public void merge(ObjectValidationDefinition objectDefinition) {
		if (!identity.equals(objectDefinition.identity)) {
			throw new BuildingException("only can merge definitions under the same Meta class.");
		}

		for (ValidationDefinition validationDefinition : objectDefinition.definitions) {
			if (validationDefinition instanceof AbandonedDefinition) {
				AbandonedDefinition abandonedDefinition = (AbandonedDefinition) validationDefinition;
				if (abandonedDefinition.isAbandoned()) {
					log.info("definition will overrided as suppressed {}", validationDefinition);

					definitions.remove(validationDefinition);
					continue;
				}
			}
			addPropertyDefinition(validationDefinition);
		}
	}

	public void addPropertyDefinition(ValidationDefinition definition) {
		if (definitions.contains(definition)) {
			log.info("will override definition {}", definition.toString());
			definitions.remove(definition);
		}
		definitions.add(definition);

	}

}
